package bjut.zrpc.core.optimization.serializer;

import bjut.zrpc.core.optimization.interfaces.Serializer;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;

/**
 * @Author: zhuzhiming
 * @Date: 2022/6/24 12:51
 */
public class ProtostuffSerializer implements Serializer {

    private static final LinkedBuffer BUFFER = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);

    @Override
    public byte[] serialize(Object data) {

        Schema schema = RuntimeSchema.getSchema(data.getClass());

        byte[] byteArray;
        try {
            byteArray = ProtostuffIOUtil.toByteArray(data, schema, BUFFER);
        } finally {
            BUFFER.clear();
        }
        return byteArray;
    }

    @Override
    public <T> T deSerialize(byte[] bytes, Class<T> cls) {

        Schema<T> schema = RuntimeSchema.getSchema(cls);
        T t = schema.newMessage();
        ProtostuffIOUtil.mergeFrom(bytes, t, schema);
        return t;
    }
}
